package com.hongfeng.support.util.file;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.hongfeng.support.util.config.PropertiesUtil;

public class FileUploadUtil {

	/**
	 * 上传文件，返回文件相对路径
	 * 
	 * @param request
	 * @param childPath
	 * @return
	 * @throws Exception
	 */
	public static List<String> fileUpload(HttpServletRequest request,
			String childPath) throws Exception {

		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区，超过后写入临时文件
		factory.setSizeThreshold(10240000);
		// 设置临时文件存储位置
//		String rootPath = request.getSession().getServletContext()
//				.getRealPath("/");
//		childPath = "/uploads/" + childPath;
//		File file = new File(rootPath + childPath);
		String rootPath = PropertiesUtil.getConfig("image.rootpath");
		childPath = PropertiesUtil.getConfig("image.relativepath") + childPath;
		File file = new File(rootPath + childPath);
		if (!file.exists()) {
			file.mkdirs();
		}
		factory.setRepository(file);
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置单个文件的最大上传值
		upload.setFileSizeMax(10002400000l);
		// 设置整个request的最大值
		upload.setSizeMax(10002400000l);
		upload.setHeaderEncoding("UTF-8");

		List<?> items = upload.parseRequest(request);
		List<String> fileUrls = new ArrayList<String>(items.size());
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		for (int i = 0; i < items.size(); i++) {
			FileItem item = (FileItem) items.get(i);
			String itemName = item.getName();
			if (itemName == null) {
				continue;
			}
			String fileType = itemName.substring(itemName.lastIndexOf("."));
			String fileName = format.format(new Date()) + fileType;
			String relativePath = childPath + "/" + fileName;
			String absolutePath = rootPath + childPath + "/" + fileName;
			// 保存文件
			if (!item.isFormField() && item.getName().length() > 0) {
				item.write(new File(absolutePath));
				fileUrls.add(relativePath);
			}
		}
		return fileUrls;
	}
}
